import axios from 'axios';
import { Toast } from 'mint-ui';
// 创建axios实例
/* eslint-disable */
const service = axios.create({
  baseURL: process.env.BASE_API,
  headers: {'X-Squirrel-Header': 'TED'},
  timeout: 5000                  // 请求超时时间
});

var NETWORK_OFFLINE = 0;

// request拦截器
service.interceptors.request.use(config => {
  return config;
}, error => {
  if(window.navigator.onLine === false || NETWORK_OFFLINE) {
    console.log("show toast");
    Toast({
      message: '网络异常，请检查网络连接',
      duration: 2000,
      className: 'custom-toast'
    });
  }
  console.log('client err: ' + error); // for debug
  return error;
});

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    return res;
  },
  error => {
    if(window.navigator.onLine === false || NETWORK_OFFLINE) {
      Toast({
        message: '网络异常，请检查网络连接',
        duration: 2000,
        className: 'custom-toast'
      });
    } else {
      var errMsg = error + "";
      if (/timeout/i.test(errMsg)) {
        Toast({
          message: '网络异常，请检查网络连接',
          duration: 2000,
          className: 'custom-toast'
        });
      }
    }
    console.log('response err: ' + error);// for debug
    return error;
  }
);

window.addEventListener('online',  function(){
  NETWORK_OFFLINE = 0;
});
window.addEventListener('offline', function(){
  NETWORK_OFFLINE = 1;
});

export default service;
